<script setup lang="ts">
import CreateSuccess from "~/components/dialog/CreateSuccess.vue";
import { fileUploadAPI } from "~/api/fileUpload";
import { compressImageTo200KB } from "~/utils/imgZip";
import { useImageCache } from "~/composables/useImageCache";
import {
  buyerCreateCompany,
  getCompanyInfo,
  getCompanyById,
  updateCompany,
  getDict,
} from "~/api/user";
import { useRoute } from "vue-router";
import { useUserStore } from "~/store/useUser";

useSeoMeta({
  title: "企业入驻 - 技能猴子",
  ogTitle: "企业入驻 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const userStore = useUserStore();
const route = useRoute();

onMounted(async () => {
  const id = route.query.id || userStore.getUserInfo.companyId;
  if (id) {
    await getInfoById(id as string);
  } else if (userStore.getUserInfo.addCompany) {
    await getInfo();
  }
  getIndustryList();
  getRemoteRatioList();
});
const getInfo = async () => {
  try {
    const { data } = await getCompanyInfo();
    formData.value = data;
  } catch (e) {
    console.log(e);
  }
};

const getInfoById = async (id: string | number) => {
  try {
    const { data } = await getCompanyById(id);
    formData.value = data;
  } catch (e) {
    console.log(e);
  }
};

// 获取行业列表
const getIndustryList = async () => {
  try {
    const { data } = await getDict("sys_company_industry");
    industry.value = data;
    console.log(industry.value);
  } catch (e) {
    console.log(e);
  }
};

// 获取远程比例字典（与 sys_company_industry 一致的字典结构）
const getRemoteRatioList = async () => {
  try {
    const { data } = await getDict("sys_remote_ratio");
    remoteRatioOptions.value = data;
  } catch (e) {
    console.log(e);
  }
};

const formData = ref({
  logo: "",
  name: "",
  industry: "",
  staffsMin: null,
  introduce: "",
  remoteRatio: "",
  abbreviation: "",
});

const { getCoverImage } = useImageCache();

const industry = ref([]);
const rules = {
  name: [
    { required: true, message: "公司全称不能为空", trigger: "blur" },
    { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" },
    // 验证是否为空先去除所有空格
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value.trim() === "") {
          callback(new Error("公司全称不能为空"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  industry: [{ required: true, message: "请选择所处行业", trigger: "blur" }],
  introduce: [
    { required: true, message: "一句话介绍企业不能为空", trigger: "blur" },
    { min: 3, max: 200, message: "长度在 3 到 200 个字符", trigger: "blur" },
    // 验证是否为空先去除所有空格
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value.trim() === "") {
          callback(new Error("一句话介绍企业不能为空"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  logo: [{ required: true, message: "请上传企业Logo", trigger: "blur" }],
  staffsMin: [
    { required: true, message: "团队规模不能为空", trigger: "blur" },
    {
      // 使用函数验证最小不能小于1，最大不能大于10000000
      validator: (rule: any, value: any, callback: any) => {
        if (value < 1) {
          callback(new Error("团队规模不能小于1"));
        } else if (value > 10000000) {
          callback(new Error("团队规模不能大于10000000"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};
// 与 sys_company_industry 一样的字典结构：[{ dictLabel, dictValue }]
const remoteRatioOptions = ref([]);
const successDIalogShow = ref(false);
const formRef = ref(null);
const submit = async () => {
  console.log(formData.value);
  try {
    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        if (formData.value.id) {
          await updateCompany(formData.value);
          await userStore.userInfoAction();
          await userStore.getShopInfo();
          useRouter().push("/companyHome");
        } else {
          await buyerCreateCompany(formData.value);
          await userStore.getShopInfo();
          await userStore.userInfoAction();
          successDIalogShow.value = true;
        }
      }
    });
  } catch (e) {
    console.log(e);
  }
};
// 文件上传
const fileInput = ref(null);
const fileUpload = async (e: any) => {
  const file = e.target.files[0];
  const imgZip = await compressImageTo200KB(file);
  const formParams = new FormData();
  formParams.append("file", imgZip);
  const { data } = await fileUploadAPI(formParams);
  const ossId = data.ossId;
  formData.value.logo = ossId;
  fileInput.value.value = "";
};
const delUploadImg = () => {
  formData.value.logo = "";
};
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="add-form">
    <h4 class="page-title">企业信息</h4>
    <div class="form">
      <el-form ref="formRef" :model="formData" label-position="top" :rules="rules">
        <el-form-item label="公司全称" prop="name">
          <el-input v-model="formData.name" style="width: 650px; height: 48px" maxlength="50"
            placeholder="如：有声探网络科技有限公司" show-word-limit type="text" />
        </el-form-item>
        <el-form-item label="所处行业" prop="industry">
          <el-select v-model="formData.industry" style="width: 650px; height: 48px" placeholder="请选择所处行业">
            <el-option v-for="item in industry" :key="item.value" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="团队规模" prop="staffsMin">
          <el-input type="number" minlength="1" maxlength="10" min="1" v-model="formData.staffsMin"
            style="width: 650px; height: 48px" placeholder="请输入团队成员人数"></el-input>
        </el-form-item>
        <el-form-item label="一句话介绍企业" prop="introduce">
          <el-input v-model="formData.introduce" style="width: 650px; height: 120px" maxlength="200"
            placeholder="介绍企业使命、愿景、文化、业务等概括" show-word-limit type="textarea" />
        </el-form-item>
        <el-form-item label="远程状态">
          <el-select v-model="formData.remoteRatio" style="width: 650px; height: 48px" placeholder="请选择远程员工比例">
            <el-option v-for="item in remoteRatioOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业简称（选填）" v-if="false">
          <el-input v-model="formData.abbreviation" style="width: 650px; height: 48px" placeholder="请输入企业简称"
            maxlength="20" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="上传你的企业/品牌/产品 Logo" prop="logo">
          <div>
            <p class="upload">
              <span class="upload-img" v-if="formData.logo">
                <img class="img" :src="getCoverImage(formData.logo)" alt="" />
                <img @click="delUploadImg()" class="del" src="~/assets/img-del-icon.png" alt="" />
              </span>
              <span class="upload-add" v-if="!formData.logo">
                <img src="~/assets/file-add.png" alt="" />
                <input ref="fileInput" type="file" accept="image/png, image/jpeg" @input="fileUpload" />
              </span>
            </p>
            <p class="tips">
              填写企业名称后，系统将自动生成默认logo， 点击可重新上传logo。(最多1张)
            </p>
          </div>
        </el-form-item>
      </el-form>
      <span class="save" @click="submit">保存</span>
    </div>
  </div>
  <BaseFooter />
  <CreateSuccess v-if="successDIalogShow" @close="successDIalogShow = false" />
</template>

<style scoped lang="scss">
.add-form {
  padding-top: 80px;
  background: #f9f9f9;
  padding-bottom: 36px;
}

.page-title {
  font-weight: 600;
  font-size: 20px;
  color: #191e28;
  line-height: 30px;
  width: 1100px;
  margin: 0 auto;
  padding-top: 32px;
  padding-bottom: 16px;
}

.form {
  width: 1100px;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin: 0 auto;
  padding: 24px;
  box-sizing: border-box;
}

.upload {
  display: flex;

  .upload-img {
    width: 50px;
    height: 50px;
    margin-right: 12px;
    border-radius: 12px;
    overflow: hidden;
    position: relative;

    .img {
      height: 100%;
    }

    .del {
      position: absolute;
      top: 2px;
      right: 2px;
      width: 16px;
      height: 16px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: scale(1.4);
      }
    }
  }

  .upload-add {
    flex: 0 0 50px;
    height: 50px;
    position: relative;

    img {
      width: 100%;
      height: 100%;
    }

    input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
    }
  }
}

.tips {
  font-size: 12px;
  color: rgba(25, 30, 40, 0.36);
}

.save {
  width: 160px;
  height: 48px;
  background: #1dbf73;
  border-radius: 8px 8px 8px 8px;
  display: block;
  text-align: center;
  line-height: 48px;
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  margin-top: 30px;
  cursor: pointer;
}

.add-form :deep(.el-input__wrapper) {
  border-radius: 8px;
}

.add-form :deep(.el-select__wrapper) {
  width: 650px;
  border-radius: 8px;
  height: 48px;
}

.add-form :deep(.el-textarea__inner) {
  height: 100%;
}
</style>
